using System;
using System.Collections;
using System.Text;

using log4net;
using log4net.Config;

using MySql.Data.MySqlClient;
using Chat.metier;
using ChatServer;
using NHibernate;

namespace Chat.dao
{
    class ContactDAO : IContactDAO
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ContactDAO));

        #region IContactDAO Membres
        /// <summary>
        /// Retourne un user en fonction de son id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Contact getById(int id)
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                Contact contact = (Contact)session.Get(typeof(Contact), id);
                session.Close();
                return contact;
            }
            catch (Exception e)
            {
                log.Error("Contact getById" , e);
                return null;
            }
        }

        /// <summary>
        /// Retourne tous les utilisateurs
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IList getAll()
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                IList contacts = session.CreateQuery("from Contact").List();
                session.Close();
                return contacts;
            }
            catch (Exception e)
            {
                log.Error("Contact getAll", e);
                return null;
            }
        }

        
        /// <summary>
        /// Save the Contact
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        public int save(Contact contact)
        {
            ISession session = InitFramework.sessionFactory.OpenSession();
            try
            {
                ITransaction tx = session.BeginTransaction();
                int id = (int)session.Save((Object)contact);
                tx.Commit();
                session.Close();
                return id;
            }
            catch (Exception e)
            {
                log.Error("Contact save ", e);
                return -1;
            }
        }

    }
        #endregion
}
